package com.woniuxy.renters.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.core.exception.accountException.AccountException;
import com.woniuxy.core.exception.accountException.AccountExceptionCode;
import com.woniuxy.core.exception.certifiedException.CertifiedException;
import com.woniuxy.core.exception.certifiedException.CertifiedExceptionCode;
import com.woniuxy.core.exception.rentersException.RentersException;
import com.woniuxy.core.exception.rentersException.RentersExceptionCode;
import com.woniuxy.core.exception.stallException.StallException;
import com.woniuxy.core.exception.stallException.StallExceptionCode;
import com.woniuxy.core.model.Result;
import com.woniuxy.core.staticCode.StallInfoCode;
import com.woniuxy.core.staticCode.UserCode;
import com.woniuxy.core.util.HttpUtils;
import com.woniuxy.core.util.OSSUtil;
import com.woniuxy.core.util.PageInfo;
import com.woniuxy.renters.dao.RentersAccount;
import com.woniuxy.renters.dao.RentersInfo;
import com.woniuxy.renters.feign.StallInfoClient;
import com.woniuxy.renters.mapper.RentersAccountMapper;
import com.woniuxy.renters.mapper.RentersInfoMapper;
import com.woniuxy.renters.model.form.AddrentersinfoForm;
import com.woniuxy.renters.model.param.AddCarportParam;
import com.woniuxy.renters.model.param.AddrentersinsertstallParam;
import com.woniuxy.renters.model.param.IdCard;
import com.woniuxy.renters.model.param.LoadAllRentersinfoParam;
import com.woniuxy.renters.service.RentersInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.stall.dao.StallInfo;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 凌玉春
 * @since 2024年01月15日
 */
@Service
public class RentersInfoServiceImpl extends ServiceImpl<RentersInfoMapper, RentersInfo> implements RentersInfoService {
    @Autowired
    private RentersInfoMapper rentersInfoMapper;
    @Autowired
    private RentersAccountMapper rentersAccountMapper;
    @Autowired
    private StallInfoClient stallInfoClient;

    @Resource
    private OSSUtil ossUtil;

    @Override
    public IdCard rentersVerifyIdCard(String name, String idcard, Integer id) {
        if (name==null){
            throw new AccountException(AccountExceptionCode.NOT_NULL);
        }
        if (idcard==null){
            throw new AccountException(AccountExceptionCode.NOT_NULL);
        }
        System.out.println("sssssssssssssssssssssssssssssssssssssssssssssssssssssss");
        String host = "https://sfzsmyxb.market.alicloudapi.com";
        String path = "/get/idcard/checkV3";
        String method = "GET";
        String appcode = "c3066463eafd426abc402c8e9dea9709";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("name", name);
        querys.put("idcard", idcard);
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            System.out.println(response.toString());
            System.out.println("-----------------------------------------");

            System.out.println("Status Line: " + response.getStatusLine());
            Header[] headers1 = response.getAllHeaders();
            System.out.println("Headers:");
            for (Header header : headers1) {
                System.out.println(header.getName() + ": " + header.getValue());
            }
            System.out.println("Response Body:");
            String responseBody = EntityUtils.toString(response.getEntity());
            System.out.println(responseBody);
            if (responseBody==null){
                System.out.println("null");
            }
            System.out.println("---------------------------------------------");
            JSONObject jsonObject = JSONObject.parseObject(responseBody);
            System.out.println("===============================================");
            System.out.println(jsonObject);
            System.out.println("+++++++++++++++++++++++++++++++++++++++++++++");
            System.out.println(jsonObject.toJSONString());
            System.out.println("===============================================");
            int code = jsonObject.getIntValue("code");
            System.out.println(code);
            String message = jsonObject.getString("message");
            System.out.println(message);
            JSONObject data = jsonObject.getJSONObject("data");
            System.out.println(data);
            cn.hutool.json.JSONObject entries = JSONUtil.parseObj(data.toJSONString());
            System.out.println("```````````````````");
            System.out.println(entries);
            if (code == 200) {
                String orderNo = data.getString("order_no");
                System.out.println(orderNo);
                String birthday = data.getString("birthday");
                System.out.println(birthday);
                String address = data.getString("address");
                System.out.println(address);
                String sex = data.getString("sex");
                System.out.println(sex);
                String desc = data.getString("desc");
                System.out.println(desc);

                String birthdayString = idcard.substring(6, 14);
                LocalDate birthdays = LocalDate.parse(birthdayString, DateTimeFormatter.ofPattern("yyyyMMdd"));

                // 计算年龄
                LocalDate currentDate = LocalDate.now();
                int age = Period.between(birthdays, currentDate).getYears();

                System.out.println("年龄：" + age);

                QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
                wrapper.eq("renters_account_id", id);
                // 查询数据库中符合条件的一条记录
                RentersInfo rentersInfo = rentersInfoMapper.selectOne(wrapper);
                //已有身份证不能重复操作
                String rentersInfoCard = rentersInfo.getRentersInfoCard();
                if (rentersInfoCard!=null){
                    throw new AccountException(AccountExceptionCode.IDCARD_HAVEUSE);
                }
                //判断是否有重复的身份证
                QueryWrapper<RentersInfo> wrapper1 = new QueryWrapper<>();
                wrapper1.eq("renters_info_card",idcard);
                RentersInfo rentersInfo1 = rentersInfoMapper.selectOne(wrapper1);
                if (rentersInfo1!=null){
                    throw new AccountException(AccountExceptionCode.IDCARD_DUOCI);
                }
                if (rentersInfo != null) {
                    // 如果存在符合条件的记录，更新其属性值
                    rentersInfo.setRentersInfoCard(idcard);
                    rentersInfo.setRentersInfoName(name);
                    rentersInfo.setRentersInfoAge(age);
                    rentersInfo.setRentersInfoStatus(UserCode.USER_REAL_NAME_STATE.getCode());
                    String url = "https://car-port.oss-cn-chengdu.aliyuncs.com/1750393438211280896.png";
                    //设置默认头像
                    rentersInfo.setRentersInfoImg(url);
                    rentersInfoMapper.updateById(rentersInfo);
                } else {
                    // 如果不存在符合条件的记录，创建新的 UserInfo 对象并设置属性值，然后插入数据库
                    RentersInfo info = new RentersInfo();
                    info.setRentersInfoId(id);
                    info.setRentersInfoCard(idcard);
                    info.setRentersInfoName(name);
                    info.setRentersInfoStatus(UserCode.USER_REAL_NAME_STATE.getCode());
                    rentersInfoMapper.insert(info);
                }
                return new IdCard(true, orderNo, birthday, address, sex, desc);
            } else {
                System.out.println("sadnjknfjdn===sad");
                return new IdCard(false, null, null, null, null, message);
            }
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
            return new IdCard(false, null, null, null, null, "请求接口失败：" + e.getMessage());
        }
    }

    @Override
    public void updateRentersInfo(String rentersinfotel,Integer id) {
        System.out.println(rentersinfotel);
        System.out.println("===============");
        if (rentersinfotel==null){
            throw new AccountException(AccountExceptionCode.NOT_NULL);
        }
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_account_id",id);
        RentersInfo rentersInfo = rentersInfoMapper.selectOne(wrapper);
        rentersInfo.setRentersInfoPhone(rentersinfotel);
        Integer rentersAccountId = rentersInfo.getRentersAccountId();
        System.out.println(rentersAccountId);
        QueryWrapper<RentersAccount> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("renters_id",rentersAccountId);
        RentersAccount rentersAccount = rentersAccountMapper.selectOne(wrapper1);
        rentersAccount.setRentersPhone(rentersinfotel);
        rentersAccountMapper.updateById(rentersAccount);
        rentersInfoMapper.updateById(rentersInfo);
    }

    @Override
    public RentersInfo uploadImage(MultipartFile image, String id) throws IOException {
        if (image==null){
            throw new AccountException(AccountExceptionCode.NOT_NULL);
        }
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_account_id",id);
        RentersInfo rentersInfo = rentersInfoMapper.selectOne(wrapper);
        //获取文件类型
        String fileType = FileTypeUtil.getType(image.getInputStream());
        if (!fileType.equals("jpg")&&!fileType.equals("png")){
            throw new CertifiedException(CertifiedExceptionCode.PICTURE_FORMAT_ERROR);
        }
        //创建文件名称
        Snowflake snowflake = new Snowflake(1,1);
        String prefix = snowflake.nextIdStr();
        String fileName = prefix+"."+fileType;
        String url = ossUtil.uploadFile(image.getInputStream(), fileName, "car-port");
        rentersInfo.setRentersInfoImg(url);
        rentersInfoMapper.updateById(rentersInfo);
        return rentersInfo;
    }

    @Override
    public PageInfo<RentersInfo> loadAllRentersinfo(LoadAllRentersinfoParam param) {
        if (param.getPageNum()==null){
            throw new AccountException(AccountExceptionCode.NOT_NULL);
        }
        if (param.getPageSize()==null){
            throw new AccountException(AccountExceptionCode.NOT_NULL);
        }
        Page<RentersInfo> page = new Page<RentersInfo>(param.getPageNum() == null ? 1 : param.getPageNum(), param.getPageSize() == null ? 5 : param.getPageSize());
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<RentersInfo>();
        rentersInfoMapper.selectPage(page,wrapper);
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setList(page.getRecords());
        pageInfo.setPages(page.getPages());
        System.out.println(pageInfo);
        return pageInfo;
    }

    @Override
    public RentersInfo loadAllRentersinfobyName(String rentersinfoName) {
        if (rentersinfoName==null){
            throw new AccountException(AccountExceptionCode.NOT_NULL);
        }
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_info_name", rentersinfoName);
        return rentersInfoMapper.selectOne(wrapper);
    }

    @Override
    public RentersInfo loadAllRentersinfobyId(Integer rentersInfoId) {
        if (rentersInfoId==null){
            throw new AccountException(AccountExceptionCode.NOT_USERINFOID_NULL);
        }
        return  rentersInfoMapper.selectById(rentersInfoId);
    }

    @Override
    public RentersInfo loadAllRentersinfoByRentersinforPhone(String rentersinfoPhone) {
        if (rentersinfoPhone.length()==0){
            throw new AccountException(AccountExceptionCode.PHONE_NOT_NULL);
        }
        if (rentersinfoPhone.length()!=11){
            throw new AccountException(AccountExceptionCode.LENTH_WORRY);
        }
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_info_phone", rentersinfoPhone);
        return rentersInfoMapper.selectOne(wrapper);
    }

    @Override
    public void insertRentersInfo(AddrentersinfoForm form, String id) {
        if (form.getCertifiedinfoid()==null){
            throw new AccountException(AccountExceptionCode.NOT_NULL);
        }
        if (form.getStallinfoid()==null){
            throw new AccountException(AccountExceptionCode.NOT_NULL);
        }
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_info_id",id);
        RentersInfo rentersInfo = rentersInfoMapper.selectOne(wrapper);
        rentersInfo.setStallInfoId(String.valueOf(form.getStallinfoid()));
        rentersInfo.setCertifiedInfoId(form.getCertifiedinfoid());
        rentersInfoMapper.updateById(rentersInfo);
    }

    @Override
    public RentersInfo loadAllRentersInfos(String id) {
        RentersInfo rentersInfo = rentersInfoMapper.selectById(id);
        if (rentersInfo==null){
            throw  new AccountException(AccountExceptionCode.NO_USER);
        }
        return rentersInfo;
    }

    @Override
    public Boolean loadAllRentersInfoss(String id) {
        System.out.println("=================");
        RentersInfo rentersInfo = rentersInfoMapper.selectById(id);
        String rentersInfoCard = rentersInfo.getRentersInfoCard();
        if (ObjectUtil.isEmpty(rentersInfo.getRentersInfoCard())){
            return  false;
        }
        Integer status = rentersInfo.getRentersInfoStatus();
        if (status==0){
            return true;
        }
        if (status==1){
            return false;
        }
        return false;
    }

    @Override
    public void addCarport(AddCarportParam param) {
        //出租客账号是否存在
        RentersInfo rentersInfo = rentersInfoMapper.selectById(param.getRentersInfoId());
        if(rentersInfo==null){
            throw new RentersException(RentersExceptionCode.RENTERS_NO_HAVE);
        }
        //新增车位
        String stringIds = rentersInfo.getStallInfoId();
        String str=null;
        if (StringUtil.isNullOrEmpty(stringIds)){
            List<Integer> list=new ArrayList<>();
            String stallInfoId = param.getStallInfoId();
            System.out.println("oooooooooo");
            System.out.println(stallInfoId);
            list.add(Integer.parseInt(stallInfoId));
            str= list.stream().map(Objects::toString).collect(Collectors.joining("\",\"", "[\"", "\"]"));
        }else {
            JSONArray jsonArray = JSONUtil.parseArray(stringIds);
            List<Integer> list1 = jsonArray.toList(Integer.class);
            list1.add(Integer.parseInt(param.getStallInfoId()));
            str= list1.stream().map(Objects::toString).collect(Collectors.joining("\",\"", "[\"", "\"]"));
        }
        System.out.println("lllllllllllll");
        System.out.println(str);
        rentersInfo.setStallInfoId(str);
        rentersInfoMapper.updateById(rentersInfo);
    }



}
